package com.mf.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.mf.entity.Workday;
import com.mf.exception.CustomExceptionHandler;
import com.mf.mapper.WorkdayMapper;
import com.mf.service.IWorkdayService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * <p>
 * 工作日 服务实现类
 * </p>
 *
 * @author mf
 * @since 2024-05-20
 */
@Service
public class WorkdayServiceImpl extends ServiceImpl<WorkdayMapper, Workday> implements IWorkdayService {
    @Resource
    private WorkdayMapper workdayMapper;

    @Override
    public Boolean addWorkday(List<Workday> workdays) {
        if (workdays == null || workdays.isEmpty()) {
            throw new IllegalArgumentException("Workday list cannot be null or empty");
        }

        // 获取最小和最大日期
        Optional<Workday> minWorkday = workdays.stream().min(Comparator.comparing(Workday::getDate));
        Optional<Workday> maxWorkday = workdays.stream().max(Comparator.comparing(Workday::getDate));

        String minDate = minWorkday.get().getDate();
        String maxDate = maxWorkday.get().getDate();

        // 检查日期范围内是否已存在记录
        LambdaQueryWrapper<Workday> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.between(Workday::getDate, minDate, maxDate);
        List<Workday> existingWorkdays = workdayMapper.selectList(queryWrapper);

        if (!existingWorkdays.isEmpty()) {
            // 如果已存在记录，抛出异常或返回false
            throw new CustomExceptionHandler("日期已存在");
        }

        // 保存工作日记录
        workdayMapper.saveBatch(workdays);
        return true; // 返回true表示添加成功
    }

    /**
     * 查询范围内工作日
     * @param start 开始日期
     * @param end 结束日期
     */
    @Override
    public List<Workday> findWorkDayByScope(String start, String end) {
        LambdaQueryWrapper<Workday> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.between(Workday::getDate,start,end);
        return workdayMapper.selectList(queryWrapper);
    }

    /**
     * 查询范围内工作日天数
     */
    @Override
    public Integer findWorkDayByScopeSum(String start, String end) {
        LambdaQueryWrapper<Workday> queryWrapper = new LambdaQueryWrapper<>();
        System.out.println(start);
        System.out.println(end);
        queryWrapper.between(Workday::getDate,start,end);
        queryWrapper.orderByDesc(Workday::getDate);
        return workdayMapper.selectList(queryWrapper).size();
    }
}
